package org.ediba.siri.core.image.data;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.ediba.siri.core.Filter;
import org.ediba.siri.core.common.data.HibernateDomainDao;
import org.ediba.siri.core.image.domain.ImageKeyword;
import org.ediba.siri.core.test.domain.Imagekeywordtemp;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

public class HibernateImageKeywordDao extends HibernateDomainDao<ImageKeyword, Integer> implements ImageKeywordDao {

	public HibernateImageKeywordDao() {super(ImageKeyword.class);}
	
	@Override
	protected DetachedCriteria buildCriteria(Collection<Map<Filter, Object>> filters) {
		DetachedCriteria detachedCriteria = this.buildCriteria();
		
		Disjunction or = Restrictions.disjunction();
		Conjunction and;

		for (Map<Filter, Object> map : filters) {
			and = Restrictions.conjunction();
			for (Map.Entry<Filter,Object> entry: map.entrySet())
				switch (entry.getKey()){
					case WORD: and.add(Restrictions.ilike(Filter.WORD.getProperty(), (String)entry.getValue(), MatchMode.START));
					break;
					case IMAGE: detachedCriteria.createAlias(Filter.IMAGE.getCollection(),Filter.IMAGE.getProperty());
								and.add(Restrictions.eq(Filter.IMAGE.getPropertyId(), entry.getValue()));
					break;
				}
			or.add(and);
		}
		detachedCriteria.add(or);
		
		return detachedCriteria;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Imagekeywordtemp> getImageKeywordtemp() {
		DetachedCriteria dc = DetachedCriteria.forClass(Imagekeywordtemp.class);
		return this.getHibernateTemplate().findByCriteria(dc);
	}

}
